<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<%@page import="java.sql.*"%>
<%@page import="deweb.cimaplanning.misc"%>


<%@page import="deweb.cimaplanning.beans.MonthsPeriodsVersionsBean"%>
<%@page import="java.util.Vector"%>
<%@page import="deweb.cimaplanning.dto.MonthsPeriodsVersions"%>
<%@page import="com.cpi.cornpp.plants.services.PlantService"%>
<%@page import="com.cpi.cornpp.plants.dto.PlantDTO"%>
<%@page import="java.util.ArrayList"%>
<%@page import="deweb.cimaplanning.beans.POCostsBean"%>
<%@page import="deweb.cimaplanning.dto.POCosts"%>
<%@page import="java.text.DecimalFormat"%>
<%@page import="deweb.cimaplanning.beans.POPlantCostsBean"%>
<%@page import="deweb.cimaplanning.dto.POPlantCosts"%>
<%@page import="java.util.Hashtable"%>
<%@page import="deweb.cimaplanning.beans.PORegionCostsBean"%>
<%@page import="deweb.cimaplanning.dto.PORegionCosts"%><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="../css/principal.css" type="text/css"/>
<link rel="stylesheet" href="../css/secundario.css" type="text/css"/>
<title>Distribucion de Costos</title>
</head>

<body>

<form id="mainFrm" name="mainFrm" method="post" action="">
<%
boolean DEBUG = false;
if (DEBUG) out.println("<br>DEBUG ON: [" + request.getRequestURI() + "]");

com.deweb.GetProperties prop;
Connection conn = null;
Statement stmt  = null;
ResultSet rs	= null;
String sql 		= null;

//bloque de contadores y elementos de ciclo
int i;
int j;
int k;

boolean odd;

try{
    prop = new com.deweb.GetProperties(request);
    conn = prop.getDBConnection();
    stmt = conn.createStatement();
	
	sql = "";
	
	String keyId	= request.getParameter("keyId") == null ? "0" : request.getParameter("keyId");
	int frmAction	= request.getParameter("frmAction") == null ? 0 : (request.getParameter("frmAction").toString().length() == 0 ? 0 : Integer.parseInt(request.getParameter("frmAction").toString()));
	boolean print	= request.getParameter("print") == null ? false : (request.getParameter("print").toString().equals("1") ? true : false);
	
	int order	= request.getParameter("order") == null ? 1 : (request.getParameter("order").toString().length() == 0 ? 1 : Integer.parseInt(request.getParameter("order").toString()));
	String dir	= request.getParameter("dir") == null ? misc.ASC : request.getParameter("dir");
	
	if (DEBUG) {
		out.println("<br>keyId: [" + keyId + "]");
		out.println("<br>frmAction: [" + frmAction + "]");
		out.println("<br>order: [" + order + "]");
		out.println("<br>dir: [" + dir + "]");
	} 
	
	//eliminacion de registro (NA)
	String delMsg = "";
	
	//version quemada para facilitar las cosas

	keyId = "1";
	out.println("<br>Version quemada para facilidad de desarrollo: [" + keyId + "]");

	
	int versionId = Integer.parseInt(keyId);
	
	sql  = "SELECT COUNT(*) processed ";
	sql += "	FROM costs_po c, vw_v_purchases_orders_versions pov ";
	sql += "	WHERE c.purchase_order_version_id = pov.purchase_order_version_id ";
	sql += "		AND pov.version_id = " + versionId + " ";
	
	if (DEBUG) out.println("<br>sql: [" + sql + "]");
	rs = stmt.executeQuery(sql);
	
	if (rs.next()){
		if (rs.getInt("processed") == 0){
			//no hay distribucion de costos aun
			return;
		}
	}
%>
<table border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td><div class="frame_hs" id="theFrame">
      <table border="0" align="center" cellpadding="2" cellspacing="1">
        <tr>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
<%
	//lectura de los meses de la version
	MonthsPeriodsVersionsBean mbean = new MonthsPeriodsVersionsBean();
	ArrayList months 				= mbean.browse(versionId);
	MonthsPeriodsVersions m 		= null;
	
	//lectura de las plantas
	sql  = "SELECT plant_id, short_name ";
	sql += "	FROM plants ";
	sql += "	ORDER BY priority DESC ";
	
	if (DEBUG) out.println("<br>sql: [" + sql + "]");
	rs = stmt.executeQuery(sql);

	PlantDTO plant		= null;
	ArrayList alPlants	= new ArrayList(3);

	while (rs.next()){
		plant = new PlantDTO();
		
		plant.setPlantId(rs.getInt("plant_id"));
		plant.setShortName(rs.getString("short_name"));
		
		//if (DEBUG) out.println("<br>Pland ID: [" + plant.getPlantId() + "] short Name [" + plant.getShortName() + "]");
		
		alPlants.add(plant);
	}
	
	alPlants.trimToSize();

	//lectura de las PO
	POCostsBean pocBean	= new POCostsBean();
	ArrayList pos		= pocBean.browse(versionId, misc.ALL, true);
	POCosts po			= null;
	
	//lectua de los po_plants
	POPlantCostsBean ppoBean	= new POPlantCostsBean();
	ArrayList ppos				= ppoBean.browse(versionId);
	POPlantCosts ppo			= null;
	
	//se crea su hashtable para encontrar los valores segun llave:
		//purchase_order_version_id|month_period_version_id|plant_id
		
	Hashtable htppo = new Hashtable(100);
	
	for (i = 0; i < ppos.size(); i++){
		ppo = (POPlantCosts)ppos.get(i);
		
		htppo.put(ppo.getPurchaseOrderVersionId() + "|" + ppo.getMonthPeriodVersionId() + "|" + ppo.getPlantId(), 
					ppo);
		
		//if (DEBUG) out.println("<br>plant_id y plant_version_id: [" + ppo.getPlantId() + "][" + ppo.getPlantVersionId() + "] purchase_order_version_id [" + ppo.getPurchaseOrderVersionId() + "]");
	}
	
	//lectua de los po_regions
	PORegionCostsBean rpoBean	= new PORegionCostsBean(versionId, request);
	ArrayList rpos				= rpoBean.browse();
	PORegionCosts rpo			= null;
	
	//se crea su hashtable para encontrar los valores segun llave:
		//purchase_order_version_id|month_period_version_id
		
	Hashtable htrpo = new Hashtable(100);
	
	for (i = 0; i < rpos.size(); i++){
		rpo = (PORegionCosts)rpos.get(i);
		
		htrpo.put(rpo.getPurchaseOrderVersionId() + "|" + rpo.getMonthPeriodVersionId(), 
					rpo);
	}
	
	
	//empieza tabla de resultados
	
	for (i = 0; i < months.size(); i++){
		m = (MonthsPeriodsVersions)months.get(i);
%>
          <td>&nbsp;</td>
          <td colspan="10" align="center" class="cb_titulocolumna cellBorder"><%=m.getShortName() + " " + m.getYear()%></td>
<%
	}
%>
        </tr>
        <tr>
          <td rowspan="2" class="cb_titulocolumna cellBorder" title="Ordenes de Compra">OC</td>
          <td rowspan="2" class="cb_titulocolumna cellBorder" title="Tipo de Maíz">Maíz</td>
          <td rowspan="2" class="cb_titulocolumna cellBorder" title="Origen">O</td>
<%
	for (i = 0; i < months.size(); i++){
%>
          <td>&nbsp;</td>
          <td colspan="2" align="center" class="cb_titulocolumna cellBorder">PO</td>
<%
		for (j = 0; j < alPlants.size(); j++){
			plant = (PlantDTO)alPlants.get(j);
%>
          <td colspan="2" align="center" class="cb_titulocolumna cellBorder"><%=plant.getShortName()%></td>
<%
		}
%>
          <td colspan="2" align="center" class="cb_titulocolumna cellBorder">Alm.</td>
<%
	}
%>
        </tr>
        <tr>
<%
	for (i = 0; i < months.size(); i++){
%>
          <td>&nbsp;</td>
          <td align="center" class="cb_titulocolumna cellBorder">USD/Ton</td>
          <td align="center" class="cb_titulocolumna cellBorder">Ton</td>
<%
		for (j = 0; j < alPlants.size(); j++){
%>
          <td align="center" class="cb_titulocolumna cellBorder">USD/Ton</td>
          <td align="center" class="cb_titulocolumna cellBorder">Ton</td>
<%
		}
%>
          <td align="center" class="cb_titulocolumna cellBorder">USD/Ton</td>
          <td align="center" class="cb_titulocolumna cellBorder">Ton</td>
<%
	}
%>
        </tr>
<%
	//aqui se lista y hace el for para las PO
	String amount;
	String quantity;
	int monthPeriodVersionId;
	int plantId;
	
	DecimalFormat pf = new DecimalFormat("#,##0.0000");
	DecimalFormat qf = new DecimalFormat("#,##0.000");
	
	odd = false;
	
	for (i = 0; i < pos.size(); i++){
		odd = !odd;
		
		po = (POCosts)pos.get(i);
		
		//if (DEBUG) out.println("<br> PO [" + po.getCode() + "]");
		
		out.println("        <tr class=\"" + (odd ? "columnadatoNon" : "columnadatoPar") + "\">");
		out.println("          <td class=\"dw_etiqueta_campo cellBorder\">" + po.getCode() + "</td>");
		out.println("          <td class=\"dw_etiqueta_campo cellBorder\" title=\"" + po.getCornDescription() + "\">" + po.getCornCode() + "</td>");
		out.println("          <td class=\"dw_etiqueta_campo cellBorder\">" + po.getCornOriginId() + "</td>");
		
		//por cada mes
		for (j = 0; j < months.size(); j++){
			m = (MonthsPeriodsVersions)months.get(j);
			
			//si mes de la po coincide, entonces llegó en este mes
			if (po.getMonthPeriodVersionId() == m.getMonthPeriodVersionId()){
				amount 		= pf.format(po.getAmount());
				quantity	= qf.format(po.getCapacity());
			} else {
				amount		= misc.NBSP;
				quantity	= misc.NBSP;
			}
			
			out.println("          <td class=\"cleanCell\">&nbsp;</td>");
			out.println("          <td align=\"right\" class=\"cellBorder\">" + amount + "</td>");
			out.println("          <td align=\"right\" class=\"cellBorder\">" + quantity + "</td>");
			
			//detalla la distribucion de la PO en las plantas
			for (k = 0; k < alPlants.size(); k++){
				plant = (PlantDTO)alPlants.get(k);
				
				ppo = (POPlantCosts)htppo.get(po.getPurchaseOrderVersionId() + "|" + m.getMonthPeriodVersionId() + "|" + plant.getPlantId());
				
				if (ppo != null){
					amount 		= pf.format(ppo.getAmount());
					quantity	= qf.format(ppo.getTons());
				} else {
					amount		= misc.NBSP;
					quantity	= misc.NBSP;
				} 
				
				out.println("          <td align=\"right\" class=\"cellBorder\">" + amount + "</td>");
				out.println("          <td align=\"right\" class=\"cellBorder\">" + quantity + "</td>");
			}
			
			//se busca el resultado de almacen
			rpo = (PORegionCosts)htrpo.get(po.getPurchaseOrderVersionId() + "|" + m.getMonthPeriodVersionId());
			
			if (rpo != null){
				amount 		= pf.format(rpo.getAmount());
				quantity	= qf.format(rpo.getTons());
			} else {
				amount		= misc.NBSP;
				quantity	= misc.NBSP;
			} 
			
			out.println("          <td align=\"right\" class=\"cellBorder\">" + amount + "</td>");
			out.println("          <td align=\"right\" class=\"cellBorder\">" + quantity + "</td>");
		}
		
		out.println("        </tr>");
	}
		
		
%>
        </table>
    </div></td>
  </tr>
</table>
<%
}catch (SQLException e){
	String errorMsg = "";
	errorMsg  = "            <table border=\"0\" cellspacing=\"2\" cellpadding=\"2\">";
	errorMsg += "              <tr>";
	errorMsg += "                <td class=\"errorMsg\">";
	
	errorMsg += "                  Error al procesar el registro";
	errorMsg += "                  <br>Mensaje de error: " + e.getMessage();

	errorMsg += "                </td>";
	errorMsg += "              </tr>";
	errorMsg += "            </table>";
	
	out.println(misc.ERROR + "|" + errorMsg);
} finally {
    try { conn.close(); } catch (Exception e) {}
    try { stmt.close(); } catch (Exception e) {}
    try { rs.close();   } catch (Exception e) {}
}
%>
</form>
</body>
</html>
